package com.zx.controller;

import com.zx.common.ResponseCode;
import com.zx.entity.Food;
import com.zx.entity.Notice;
import com.zx.entity.User;
import com.zx.repository.NoticeRepository;
import com.zx.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
@RequestMapping("/notice")
public class NoticeController {
    @Autowired
    private NoticeRepository noticeRepository;
    @Autowired
    private UserService userService;

    @GetMapping("/list")
    public ModelAndView list(@RequestParam(value = "page", defaultValue = "0") Integer page,
                             @RequestParam(value = "size", defaultValue = "2") Integer size,
                             Map<String,Object> map){
        PageRequest request = PageRequest.of(page,size);
        Page<Notice> notice = noticeRepository.findAll(request);
        map.put("notice",notice);
        return new ModelAndView("notice/list");
    }
    @GetMapping("/addnotice")
    public ModelAndView addnotice(Map<String,Object> map,
                                  HttpSession session){
        String username = (String) session.getAttribute("loginUser");
        User user = userService.findUserInfoByUsername(username);
        map.put("user",user);
        return new ModelAndView("notice/addNotice");
    }
    @PostMapping("/saveNotice")
    public ModelAndView saveNotice(Notice notice,
                                   Map<String,Object> map){
        noticeRepository.save(notice);
        map.put("msg", ResponseCode.SAVE_SUCCESS.getDesc());
        map.put("url","/foodshare/notice/list");
        return new ModelAndView("common/success",map);
    }
    //删除公告
    @GetMapping("/delete/{foodId}")
    public ModelAndView delete(@PathVariable("foodId") Integer id,
                               Map<String,Object> map){
        Notice notice = noticeRepository.getOne(id);
        noticeRepository.delete(notice);
        map.put("msg",ResponseCode.DELETE_SUCCESS.getDesc());
        map.put("url","/foodshare/notice/list");
        return new ModelAndView("common/success",map);
    }
    //编辑公告
    @GetMapping("/list/{foodId}")
    public ModelAndView EditUser(@PathVariable("foodId") Integer id,
                                 Map<String,Object> map,
                                 HttpSession session){
        String username = (String) session.getAttribute("loginUser");
        User user = userService.findUserInfoByUsername(username);
        map.put("user",user);
        Notice notice = noticeRepository.getOne(id);
        map.put("notice",notice);
        return new ModelAndView("notice/editNotice",map);
    }
}
